package cn.db101;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author zooy
 * @since 2024/6/4-17:31
 */
public class Calculator {

    private JFrame frame = new JFrame("计算器");

    // 输入文本
    private JTextField inputText = new JTextField("0");

    private JTextField showText = new JTextField("");

    private String[] keys = {"%","C","CE","Back","1⁄x","X²","√x","÷","7","8","9",
            "X","4","5","6","-","1","2","3","+","+/-","0",".","="};

    private JButton jb1, jb2,jb3;
    private JTextField jtf1;
    private JPasswordField jtf2;

    /**
     * 操作
     */
    private String operation = "";
    /**
     * 计算过后的结果
     */
    private double result = 0;
    /**
     * 等待计算
     */
    private boolean isWaitingForOperand = false;

    public Calculator() {
        // 初始化窗口大小
        frame.setLocation(300, 200);
        frame.setSize(320, 532);
        // 设置图标
        frame.setIconImage(new ImageIcon("src/main/resources/sdh.png").getImage());
        frame.setVisible(true);

        // 设置窗口拖动
        frame.setResizable(false);

        // 设置关闭监听
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void init() {
        // 底色
        Color c1 = new Color(250, 245, 239);
        Color c2 = new Color(255, 255, 255);

        // 设置输入文本面板
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());

        // 添加文本
        // 设置展示文本
        showText.setFont(new Font("楷体", Font.PLAIN, 16));
        showText.setHorizontalAlignment(JTextField.RIGHT);
        showText.setEditable(false);
        showText.setBorder(null);
        showText.setBackground(c1);
        // 设置高度
        showText.setPreferredSize(new Dimension(320, 60));
        inputPanel.add(showText, BorderLayout.NORTH);

        // 设置文本样式
        inputText.setFont(new Font("楷体", Font.BOLD, 25));
        inputText.setHorizontalAlignment(JTextField.RIGHT);
        inputText.setEditable(false);
        inputText.setBorder(null);
        inputText.setBackground(c1);
        // 设置高度
        inputText.setPreferredSize(new Dimension(320, 60));
        inputPanel.add(inputText, BorderLayout.SOUTH);

        // 设置按键面板
        JPanel keyPanel = new JPanel();
        keyPanel.setLayout(new GridLayout(6, 4, 2, 2));
        keyPanel.setBackground(c1);

        CalcActionListener calcActionListener = new CalcActionListener();

        // 添加button
        for (int i = 0; i < 8; i++) {
            JButton button = new ButtonRound(keys[i], c1);
            button.setPreferredSize(new Dimension(75, 50));
            keyPanel.add(button);
            button.setBackground(c1);
            button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            button.addActionListener(calcActionListener);
        }

        for (int i = 8; i < keys.length; i++) {
            JButton button;
            if ((i + 1) % 4 == 0) {
                button = new ButtonRound(keys[i], c1);
            } else {
                button = new ButtonRound(keys[i], c2);
            }
            keyPanel.add(button);

            button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            button.setBorderPainted(false);
            button.addActionListener(calcActionListener);
        }

        frame.add(inputPanel, BorderLayout.NORTH);
        frame.add(keyPanel);

    }

    private class CalcActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if ("0123456789.".contains(command)) {
                /*if(isWaitingForOperand) {
                    inputText.setText(inputText.getText() + command);
                } else {
                    showText.setText(showText.getText() + command);
                }*/
                if (inputText.getText().equals("0")) {
                    inputText.setText(command);
                } else {
                    inputText.setText(inputText.getText() + command);
                }
            } else if ("+-X÷".contains(command)) {
                if (isWaitingForOperand) {
                    performOperation();
                    showText.setText(inputText.getText() + command);
                } else {
                    if (!"".equals(inputText.getText())
                            && !"0".equals(inputText.getText())) {
                        result = Double.parseDouble(inputText.getText());
                        showText.setText(inputText.getText() + command);
                    } else {
                        result = Double.parseDouble(showText.getText());
                        showText.setText(showText.getText() + command);
                    }
                }
                inputText.setText("");
                isWaitingForOperand = true;
                operation = command;
            } else if ("%".equals(command)) {
                if (result != 0) {
                    inputText.setText(String.valueOf(Integer.parseInt(inputText.getText())* 1.0 / 100));
                    //performOperation();
                }
            } else if (("=").equals(command)) {
                if (!isWaitingForOperand) {
                    JOptionPane.showMessageDialog(frame, "请输入数字!", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    showText.setText(showText.getText() + inputText.getText() + "=");
                    performOperation();
                    isWaitingForOperand = false;
                }
            } else if ("C".equals(command)) {
                inputText.setText("");
                showText.setText("");
                result = 0;
                isWaitingForOperand = false;
                operation = "";
            } else if ("+/-".equals(command)) {
                if (!inputText.getText().isEmpty()) {
                    // 进行数据负数处理
                    if (inputText.getText().startsWith("-")) {
                        inputText.setText(inputText.getText().substring(1));
                    } else {
                        inputText.setText("-" + inputText.getText());
                    }
                }
            } else if ("1⁄x".equals(command)) {
                operation = "1⁄x";
                performOperation();
            } else if ("X²".equals(command)) {
                operation = "X²";
                performOperation();
            } else if ("√x".equals(command)) {
                operation = "√x";
                performOperation();
            } else if ("Back".equals(command)) {
                if (!inputText.getText().isEmpty()) {
                    // 进行数据负数处理
                    inputText.setText(inputText.getText().substring(0, inputText.getText().length() - 1));
                }
            }
        }
    }

    private void performOperation() {
        try {
            double operand = Double.parseDouble(inputText.getText());
            switch (operation) {
                case "+":
                    result += operand;
                    break;
                case "-":
                    result -= operand;
                    break;
                case "X":
                    result *= operand;
                    break;
                case "%":
                    result = operand * 1.0 / 100;
                    break;
                case "+/-":
                    result = -result;
                    break;
                case "1⁄x":
                    if (operand != 0) {
                        result = 1.0 / operand;
                    } else {
                        JOptionPane.showMessageDialog(frame, "Cannot divide by zero!", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    break;
                case "X²":
                    result = Math.pow(operand, 2);
                    break;
                case "√x":
                    result = Math.sqrt(operand);
                    break;
                case "÷":
                    if (operand != 0) {
                        result /= operand;
                    } else {
                        JOptionPane.showMessageDialog(frame, "Cannot divide by zero!", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    break;
            }
            String resultStr = String.valueOf(result);
            if (resultStr.endsWith(".0")) {
                inputText.setText(resultStr.substring(0, resultStr.length() - 2));
            } else {
                inputText.setText(resultStr);
            }
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(frame, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void LoginFrameWindow() {
        JFrame jFrame = new JFrame();
        jFrame.setTitle("登录界面");

        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));


        JLayeredPane layeredPane = new JLayeredPane();
        contentPane.add(layeredPane, BorderLayout.CENTER);

        jFrame.add(contentPane);

        // 账户
        JLabel jLabel1 = new JLabel("账号：");
        jLabel1.setBounds(80, 80, 40, 18);
        layeredPane.add(jLabel1);

        jtf1 = new JTextField(10);
        jtf1.setBounds(140, 81, 176, 19);
        layeredPane.add(jtf1);

        // 密码
        JLabel jLabel2 = new JLabel("密码：");
        jLabel2.setBounds(80, 120, 72, 18);
        layeredPane.add(jLabel2);

        jtf2 = new JPasswordField(10);
        jtf2.setEchoChar('*');
        jtf2.setBounds(140, 121, 176, 19);
        layeredPane.add(jtf2);

        // 操作按钮
        jb1 = new JButton("提交");
        jb1.setBounds(80, 160, 72, 23);
        layeredPane.add(jb1);

        jb2 = new JButton("重置");
        jb2.setBounds(160, 160, 72, 23);
        layeredPane.add(jb2);

        jb3 = new JButton("注册");
        jb3.setBounds(240, 160, 72, 23);
        layeredPane.add(jb3);

        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username =jtf1.getText();
                String passwd =new String(jtf2.getPassword());

                System.out.println("用户名是："+username);
                System.out.println("密码是："+passwd);

                if (username.equals("admin") && passwd.equals("123456")){
                    JFrame jf2 = jFrame;
                    JLabel jl2 =new JLabel("恭喜你，登录成功");
                    jl2.setFont(new Font("宋体",Font.PLAIN,35));
                    jf2.add(jl2);
                    jf2.setSize(500,500);
                    jf2.setLocationRelativeTo(null);
                    jf2.setVisible(true);
                }
                else {
                    JOptionPane.showMessageDialog(null,"登录失败","失败",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        jb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jtf1.setText("");
                jtf2.setText("");
            }
        });

        jb3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        jFrame.setVisible(true);

        jtf1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username =jtf1.getText();
                String passwd =new String(jtf2.getPassword());

                if (passwd.equals(""));
                JOptionPane.showConfirmDialog(null,"请输入密码","密码缺失",JOptionPane.INFORMATION_MESSAGE);
                jtf2.requestFocusInWindow();
            }
        });

        jFrame.setVisible(true);
        jFrame.setSize(400,400);
        jFrame.setLocationRelativeTo(null);
    }

    public void register()  {

        JFrame jFrame = new JFrame();
        jFrame.setTitle("注册界面");

        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));


        JLayeredPane layeredPane = new JLayeredPane();
        contentPane.add(layeredPane, BorderLayout.CENTER);

        jFrame.add(contentPane);

        // 用户名
        JLabel uLabel = new JLabel("用户名：");
        uLabel.setBounds(80, 80, 70, 18);
        layeredPane.add(uLabel);

        JTextField uField = new JTextField();
        uField.setBounds(140, 81, 176, 19);
        layeredPane.add(uField);

        // 密码
        JLabel pLabel = new JLabel("密    码：");
        pLabel.setBounds(80, 120, 72, 18);
        layeredPane.add(pLabel);

        JTextField pField = new JTextField();
        pField.setBounds(140, 121, 176, 19);
        layeredPane.add(pField);

        // 手机号
        JLabel tLabel = new JLabel("手机号：");
        tLabel.setBounds(80, 160, 72, 18);
        layeredPane.add(tLabel);

        JTextField tField = new JTextField();
        tField.setBounds(140, 161, 176, 19);
        layeredPane.add(tField);

        // 性别
        JLabel gLabel = new JLabel("性   别：");
        gLabel.setBounds(80, 200, 72, 18);
        layeredPane.add(gLabel);

        JRadioButton maleBtn = new JRadioButton("男", true);
        maleBtn.setBounds(140, 201, 60, 19);
        layeredPane.add(maleBtn);

        JRadioButton femaleBtn = new JRadioButton("女", false);
        femaleBtn.setBounds(210, 201, 60, 19);
        layeredPane.add(femaleBtn);

        // 注册按钮
        JButton regisBtn = new JButton("注册");
        regisBtn.setBounds(80, 241, 72, 23);
        layeredPane.add(regisBtn);

        // 返回登录页面
        JButton backBtn = new JButton("返回登录页面");
        backBtn.setBounds(200, 241, 120, 23);
        layeredPane.add(backBtn);

        backBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        jFrame.setVisible(true);
        jFrame.setSize(500,500);

        jFrame.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        new Calculator().init();
    }

}
